#!/system/bin/sh

#================================================================
#   Copyright (C) 2023 Sangfor Ltd. All rights reserved.
#   
#   文件名称：common_vars.sh
#   创 建 者：宋耀
#   创建日期：2023年07月10日
#   描    述：
#
#================================================================

. /etc/os-release
# Common File Paths
SSHD_CFG='/etc/ssh/sshd_config'
PWQUAL_CNF='/etc/security/pwquality.conf'
PASS_AUTH='/etc/pam.d/common-password'
ALLOW='/etc/hosts.allow'
DENY='/etc/hosts.deny' 
GROUP='/etc/group'
PASSWD='/etc/passwd'
SHADOW='/etc/shadow'
GSHADOW='/etc/gshadow'
PROFILE='/etc/profile' 
LOGIN_DEFS='/etc/login.defs'
PASS_AUTH='/etc/pam.d/common-password /etc/pam.d/common-account'
BRC="/etc/bash.bashrc"
AUDIT_RULES='/etc/audit/audit.rules'
AUDIT_RULES_ORI='/etc/audit/rules.d/audit.rules'
AUDITD_CNF='/etc/audit/auditd.conf'

test_apt_installed() {
  local apt="$1"
  [[ $(dpkg -l $apt 2>/dev/null) ]] || return 2    
}

# 检查apt包是未安装
test_apt_uninstalled() {
  local apt="$1"
  [[ $(dpkg -l $apt 2>/dev/null) ]] || return 0 && return 1
}

test_rpm_installed() {
  local rpm="$1"
  rpm -qa "$rpm" | grep -qe "^${rpm}" || return 2
}

# 检查apt包是未安装
test_rpm_uninstalled() {
  local rpm="$1"
   rpm -q ${rpm} | grep -q "not installed" || return
}

# 检查服务是自启
test_service_enabled(){
  local service="$1"
  systemctl is-enabled "${service}" 2>&1 | grep -q 'enabled' || return 
}

# 检查服务不是自启
test_service_disable(){
  local service="$1"
  systemctl is-enabled "${service}" 2>&1 | egrep -q 'disabled|Failed|indirect' || return
}

# 检查服务是开启状态
test_service_active(){
  local service="$1"
  systemctl is-active "${service}" 2>&1 | grep -qw 'active'  || return 
}

# 检查服务不是开启状态
test_service_failed(){
  local service="$1"
  systemctl is-failed "${service}" 2>&1 | grep -qw 'inactive' || return
}

test_service_enabled_norun(){
  local service=$1
  test_service_disable $service && test_service_failed $service || return 
}


if [[ "$ID" = "ubuntu" ]];then
  PASS_AUTH='/etc/pam.d/common-password /etc/pam.d/common-account'
  BRC="/etc/bash.bashrc"
  installed=test_apt_installed
elif [[ "$ID" == "centos" ]];then
  PASS_AUTH='/etc/pam.d/password-auth  /etc/pam.d/system-auth'
  BRC="/etc/bashrc"
  installed=test_rpm_installed
fi

##################入侵防范###############################
#应通过设定终端接入方式或网络地址范围对通过网络进行管理的管理终端进行限制
test_hosts_config() {
  local allow_configured=false
  local deny_configured=false

  # 检查hosts.allow是否配置
  if grep -Eiq '^\s*ALL:[[:space:]]*[0-9./]+\b' /etc/hosts.allow; then
    allow_configured=true
  fi

  # 检查hosts.deny是否配置
  if grep -Eiq '^\s*ALL:[[:space:]]*ALL\b' /etc/hosts.deny; then
    deny_configured=true
  fi

  # 如果hosts.allow配置了，但hosts.deny没有配置，则不合规
  if $allow_configured && ! $deny_configured; then
    return 1
  fi

  # 如果hosts.allow和hosts.deny都配置了，且hosts.deny配置为ALL:ALL，则合规
  if $allow_configured && $deny_configured; then
    local deny_rule=$(grep -Ei '^\s*ALL:[[:space:]]*ALL\b' /etc/hosts.deny)
    if [[ "$deny_rule" == "ALL: ALL" ]]; then
      return 0
    else
      return 1
    fi
  fi

  # 其他情况不合规
  return 1
}

#应关闭不需要的系统服务、默认共享和高危端口
test_off_unneeded_services_port(){
  # 检查不需要的系统服务是否已关闭
  test_service_enabled_norun telnet || return
  test_service_enabled_norun rsh || return
  test_service_enabled_norun ntalk || return
  test_service_enabled_norun dovecot || return

  # 检查默认共享是否已关闭
  test_service_enabled_norun smb || return
  test_service_enabled_norun rpcbind || return
  test_service_enabled_norun nfs-server  || return

  # 检查高危端口是否开放
  high_risk_ports=("21" "23" "25" "111" "427" "631")
  for port in "${high_risk_ports[@]}"; do
      ss -tuln | grep -q ":$port"  || return 0 && return 1 # 如果高危端口开放，不合规
  done
}

#应遵循最小安装的原则，仅安装需要的组件和应用程序
test_minimal_install(){
  if [[ "$ID" = "ubuntu" ]];then
    test_apt_uninstalled "xserver-xorg*" || return
    test_apt_uninstalled "avahi" || return
    test_apt_uninstalled "cpus" || return
    test_apt_uninstalled "isc-dhcp-server" || return
    test_apt_uninstalled "slapd" || return
    test_apt_uninstalled "nfs-kernel-server" || return
    test_apt_uninstalled "bind9" || return
    test_apt_uninstalled "vsftpd" || return
    test_apt_uninstalled "dovecot-imapd" || return
    test_apt_uninstalled "samba" || return
    test_apt_uninstalled "squid" || return
    test_apt_uninstalled "snmpd" || return
    test_apt_uninstalled "rsync" || return
    test_apt_uninstalled "nis" || return
    test_apt_uninstalled "ypbind" || return
    test_apt_uninstalled "rsh-client" || return
    test_apt_uninstalled "talk" || return
    test_apt_uninstalled "telnet" || return
    test_apt_uninstalled "ldap-utils" || return
    test_apt_uninstalled "rpcbind" || return
  elif [[ "$ID" == "centos" ]];then
    test_rpm_uninstalled "xinetd" || return
    test_rpm_uninstalled "xorg-x11-server*" || return
    test_rpm_uninstalled "avahi" || return
    test_rpm_uninstalled "cpus" || return
    test_rpm_uninstalled "dhcp" || return
    test_rpm_uninstalled "openldap-servers" || return
    test_rpm_uninstalled "bind" || return
    test_rpm_uninstalled "vsftpd" || return
    test_rpm_uninstalled "httpd" || return
    test_rpm_uninstalled "dovecot" || return
    test_rpm_uninstalled "samba" || return
    test_rpm_uninstalled "squid" || return
    test_rpm_uninstalled "net-snmp" || return
    test_rpm_uninstalled "ypserv" || return
    test_rpm_uninstalled "telnet-server" || return
    test_rpm_uninstalled "rsync" || return
    test_rpm_uninstalled "ypbind" || return
    test_rpm_uninstalled "rsh" || return
    test_rpm_uninstalled "talk" || return
    test_rpm_uninstalled "telnet" || return
    test_rpm_uninstalled "openldap-clients" || return
  fi
}

#应能发现可能存在的已知漏洞，并在经过充分测试评估后，及时修补漏洞

#能够检测到对重要节点进行入侵的行为，并在发生严重入侵事件时提供报警


##################安全审计###############
#应启用安全审计功能，审计覆盖到每个用户，对重要的用户行为和重要安全事件进行审计
test_audit_run(){
    if [[ "$ID" = "ubuntu" ]];then
        # 检查是否安装了auditd服务
        test_apt_installed "auditd" && test_apt_installed "audispd-plugins" || return 2
    elif [[ "$ID" == "centos" ]];then
        test_rpm_installed "audit" && test_rpm_installed  "audit-libs" || return
    fi
}

test_rsyslog_run(){
  if [[ "$ID" = "ubuntu" ]];then
        # 检查是否安装了rsyslog服务
        test_apt_installed "rsyslog" || return 2
    elif [[ "$ID" == "centos" ]];then
        test_rpm_installed "rsyslog" || return 2
    fi
}

test_audit_and_logging() {
    test_audit_run || return 2
    test_service_active auditd 

    # 检查是否启用了rsyslog
    test_rsyslog_run || return 2
    test_service_active rsyslog 
    
    # 检查是否配置了审计规则来收集用户的文件删除事件、系统管理范围更改和用户/组信息修改事件
    cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+delete" | egrep "\-S[[:space:]]+unlink" \
  | egrep "\-F[[:space:]]+arch=b(32|64)" | egrep "\-S[[:space:]]+unlinkat" | egrep "\-S[[:space:]]+rename" \
  | egrep "\-S[[:space:]]+renameat" | egrep "\-F[[:space:]]+auid>=1000" \
  | egrep "\-F[[:space:]]+auid\!=4294967295" \
  | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" ||  return

  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+identity" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/group" || return
  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+identity" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/passwd" || return
  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+identity" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/gshadow" || return
  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+identity" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/shadow" || return
  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+identity" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/security\/opasswd" || return

  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+scope" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/sudoers" ||  return
  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+scope" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/sudoers.d\/" ||  return
}

#审计记录应包括事件的日期和时间、用户、事件类型、事件是否成功及其他与审计相关的信息
test_audit_other() {
    # 检查是否启用了auditd服务
    test_audit_run || return 2
    test_service_active auditd

    #捕获系统日期和/或时间被修改的事件。
    cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+time-change" | egrep "\-S[[:space:]]+settimeofday" \
  | egrep "\-S[[:space:]]+adjtimex" | egrep "\-F[[:space:]]+arch=b(32|64)" | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" ||  return

  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+time-change" | egrep "\-F[[:space:]]+arch=b(32|64)" \
  | egrep "\-S[[:space:]]+clock_settime" | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" || return

  cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+time-change" | egrep "\-p[[:space:]]+wa" \
  | egrep -q "\-w[[:space:]]+\/etc\/localtime" || return

    #监视文件权限、属性、所有权和组的更改
    cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+perm_mod" | egrep "\-S[[:space:]]+chmod" \
  | egrep "\-S[[:space:]]+fchmod" | egrep "\-S[[:space:]]+fchmodat" | egrep "\-F[[:space:]]+arch=b(32|64)" \
  | egrep "\-F[[:space:]]+auid>=1000" | egrep "\-F[[:space:]]+auid\!=4294967295" \
  | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" \
 ||  return

 cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+perm_mod" | egrep "\-S[[:space:]]+chown" \
  | egrep "\-S[[:space:]]+fchown" | egrep "\-S[[:space:]]+fchownat" | egrep "\-S[[:space:]]+fchown" \
  | egrep "\-F[[:space:]]+arch=b(32|64)" | egrep "\-F[[:space:]]+auid>=1000" | egrep "\-F[[:space:]]+auid\!=4294967295" \
  | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" \
 ||  return

 cut -d\# -f1 ${AUDIT_RULES} ${AUDIT_RULES_ORI} | egrep "\-k[[:space:]]+perm_mod" | egrep "\-S[[:space:]]+setxattr" \
  | egrep "\-S[[:space:]]+lsetxattr" | egrep "\-S[[:space:]]+fsetxattr" | egrep "\-S[[:space:]]+removexattr" \
  | egrep "\-S[[:space:]]+lremovexattr" | egrep "\-S[[:space:]]+fremovexattr" | egrep "\-F[[:space:]]+arch=b(32|64)" \
  | egrep "\-F[[:space:]]+auid>=1000" | egrep "\-F[[:space:]]+auid\!=4294967295" \
  | egrep -q "\-a[[:space:]]+always,exit|\-a[[:space:]]+exit,always" \
 ||  return  
}

#应对审计记录进行保护，定期备份，避免受到未预期的删除、修改或覆盖等
test_audit_log_storage_size(){
  test_audit_run || return 2
  test_service_active auditd
  cut -d\# -f1 ${AUDITD_CNF} | egrep -q "max_log_file[[:space:]]|max_log_file=" || return
}

#应保护审计进程，避免受到未预期的中断
test_audit_rsyslog_run(){
  test_audit_run || return 2
  test_service_active auditd 

  # 检查是否启用了rsyslog
  test_rsyslog_run || return 2
  test_service_active rsyslog 
}

##################访问控制############### 

default_user_accounts(){
  banned_accounts=("adm" "bin" "daemon" "ftp" "games" "lp" "mail" "news" "nobody" "systemd-network" "systemd-resolve" "uucp" "www-data")
  for account in "${banned_accounts[@]}"; do
        if getent passwd $account &>/dev/null; then
            account_status=$(passwd -S $account | awk '{print $2}')
            if [[ $account_status != "L" ]]; then
                return 1
            fi
        fi
    done
}

#应重命名或删除默认账户，修改默认账户的默认口令
test_default_accounts() {
  # 1. 检查SSH直接登录root账号是否禁止
  [[ $(grep -Ei '^\s*PermitRootLogin\s+no' ${SSHD_CFG}) ]] || return

  # 2. 检查是否有系统默认账户和数据库帐户能够登录
  default_user_accounts

  # 3. 进行弱密码检测如果检测到弱密码，则不合规信息
  #长度大于14
  [[ $(egrep "^minlen[[:space:]]+=[[:space:]]" ${PWQUAL_CNF} | awk '{print $NF}') -ge 14 ]] || return
  #复杂度数字大小写、其他
  [[ $(grep -E '^\s*[duol]credit\s*' ${PWQUAL_CNF}) ]] || return
}

#访问控制的粒度应达到主体为用户级或进程级，客体为文件、数据库表级
test_file_perms() {
  local file="${1}"
  local pattern="${2}"
  stat -L -c "%a" ${file} | grep -qE "^${pattern}$"
}

test_root_owns() {
  local file="${1}"
  stat -L -c "%u %g" ${file} 2>/dev/null | grep -q '0 0' 
}

test_permissions_0644_root_root() {
  local file=$1
  test_root_owns ${file} || return
  test_file_perms ${file} 644 || return
}

test_permissions_0600_root_root() {
  local file=$1
  test_root_owns ${file} || return
  test_file_perms ${file} 600 || return
}

#访问控制的粒度应达到主体为用户级或进程级，客体为文件、数据库表级
test_importance_file_permissions(){
  test_file_perms ${ALLOW} 644 &&  test_root_owns ${ALLOW} || return
  test_file_perms ${DENY} 644 &&  test_root_owns ${DENY} || return
  test_file_perms ${GROUP} 644 &&  test_root_owns ${GROUP} || return
  test_file_perms ${PASSWD} 644 &&  test_root_owns ${PASSWD} || return
  test_file_perms ${SHADOW} 400 &&  test_root_owns ${SHADOW} || return
  test_file_perms ${GSHADOW} 400 &&  test_root_owns ${GSHADOW} || return
  test_file_perms ${SSHD_CFG} 600 &&  test_root_owns ${GSHADOW} || return
  test_file_perms ${PROFILE} 644 &&  test_root_owns ${PROFILE} || return
}

#home相关通用函数
test_users_home() {
  local check_type="$1"
  awk -F: '($1!~/(root|halt|sync|shutdown|nfsnobody)/ && $7!~/^(\/usr)?\/sbin\/nologin(\/)?$/ && $7!~/(\/usr)?\/bin\/false(\/)?$/) { print $1 " " $6 }' $PASSWD | while read -r user dir; do
      if [ ! -d "$dir" ]; then
          return 1
      else
          case "$check_type" in
              "own")
                  owner=$(stat -L -c "%U" "$dir")
                  if [ "$owner" != "$user" ]; then
                      return 1
                  fi
                  ;;
              "permissions")
                  dirperm=$(stat -L -c "%A" "$dir")
                  if [ "$(echo "$dirperm" | cut -c6)" != "-" ] || \
                     [ "$(echo "$dirperm" | cut -c8)" != "-" ] || \
                     [ "$(echo "$dirperm" | cut -c9)" != "-" ] || \
                     [ "$(echo "$dirperm" | cut -c10)" != "-" ]; then
                      return 1
                  fi
                  ;;
              "dot")
                  for file in "$dir"/.*; do
                      if [ ! -h "$file" ] && [ -f "$file" ]; then
                          fileperm=$(stat -L -c "%A" "$file")
                          if [ "$(echo "$fileperm" | cut -c6)" != "-" ] || \
                             [ "$(echo "$fileperm" | cut -c9)" != "-" ]; then
                              return 1
                          fi
                      fi
                  done
                  ;;
              "forward")
                  file="$dir/.forward"
                  if [ ! -h "$file" ] && [ -f "$file" ]; then
                      return 1
                  fi
                  ;;
              "netrc")
		  file="$dir/.netrc"
        	  if [ ! -h "$file" ] && [ -f "$file" ]; then
        	      if stat -L -c "%A" "$file" | cut -c4-10 | grep -Eq '[^-]+'; then
			return 1
        	      fi
        	  fi
		  ;;
              "rhosts")
		  file="$dir/.rhosts"
       		   if [ ! -h "$file" ] && [ -f "$file" ]; then
			return 1
       		   fi
                  ;;
          esac
      fi
  done 
}

#应对登录的用户分配账户和权限
test_user_permissions() {
  # 检查umask设置
  passing=""

  grep -Eiq '^\s*UMASK\s+(0[0-7][2-7]7|[0-7][2-7]7)\b' $LOGIN_DEFS && \
  grep -Eqi '^\s*USERGROUPS_ENAB\s*"?no"?\b' $LOGIN_DEFS && \
  grep -Eq '^\s*session\s+(optional|requisite|required)\s+pam_umask\.so\b' /etc/pam.d/common-session && \
  grep -REiq '^\s*UMASK\s+\s*(0[0-7][2-7]7|[0-7][2-7]7|u=(r?|w?|x?)(r?|w?|x?)(r?|w?|x?),g=(r?x?|x?r?),o=)\b' /etc/profile* $BRC && passing=true

  if [ "$passing" = true ]; then
    return 0 # 合规，返回0
  else
    return 1 # 不合规，返回1
  fi

  # 检查每个用户的home目录权限
  test_users_home "permissions"
}

#应及时删除或停用多余的、过期的账户，避免共享账户的存在
test_unused_accounts() {
  default_user_accounts

  local unused_db_accounts=("postgres")  # 添加其他不需要禁用登陆的数据库账户
  for db_account in "${unused_db_accounts[@]}"; do
        if getent passwd $db_account &>/dev/null; then
        account_status=$(passwd -S $db_account | awk '{print $2}')
          if [[ $account_status != "L" ]]; then
            return 1
          fi
        fi
  done

  # 检查是否锁定或删除shutdown和halt帐户
  local unused_close_accounts=("shutdown" "halt")
  for close_account in "${unused_close_accounts[@]}"; do
        if getent passwd $close_account &>/dev/null; then
        account_status=$(passwd -S $close_account | awk '{print $2}')
          if [[ $account_status != "L" ]]; then
            return 1
          fi
        fi
  done
  return 0  # 合规
}

#应授予管理用户所需的最小权限，实现管理用户的权限分离
test_sudo_access(){
  # 1. 检查su命令是否受限制
  [[ $(grep -E '^\s*(auth\s+required\s+pam_wheel\.so|auth\s+required\s+pam_group\.so)' /etc/pam.d/su) ]] || return 
 
  # 2. 检查/etc/sudoers配置的sudo权限
  [[ -z $(grep -E '^\s*[^#]+ALL=' /etc/sudoers | grep -v 'ALL=(ALL)') ]] || return
}

# ssh公私钥公共函数
test_ssh_keys_permissions(){
  local keys=$1
  for keys in $(find /etc/ssh -xdev -type f -name "$keys" -exec ls {} \;);do
        if [[ "$keys" =~ "pub" ]];then
          test_permissions_0644_root_root $keys
        else
          test_permissions_0600_root_root $keys
        fi  
  done
}

#应由授权主体配置访问控制策略，访问控制策略规定主体对客体的访问规则
test_access_control_policy() {
  # 1. 检查用户home目录权限
  test_users_home "permissions"

  # 2. 检查无主文件或文件夹的所有权
  [[ -z $(df --local -P | awk {'if (NR!=1) print $6'} | xargs -I '{}' find '{}' -xdev -nouser) ]] || return
 
  # 3. 检查ssh主机公钥文件的权限和所有权
  test_ssh_keys_permissions "ssh_host_*_key.pub"
  # 4. 检查ssh主机私钥文件的权限和所有权
  test_ssh_keys_permissions "ssh_host_*_key"
 
}

##############身份鉴别##############

#应对登录的用户进行身份标识和鉴别，身份标识具有唯一性，身份鉴别信息具有复杂度要求并定期更换
test_password_security() {
    # 1. 检查是否存在空密码账户
   [[ -z $(awk -F':' '($2 == "") { print $1 }' ${SHADOW}) ]] || return 
    
    # # 2. 检查身份标识(UID)具有唯一性
    [[ $(awk -F: '($3 == 0) { print $1 }' $PASSWD) == "root" ]] || return
    
    # # 3. 设置密码复杂度要求
    [[ $(grep -E '^\s*[duol]credit\s*' ${PWQUAL_CNF}) ]] || return
    
    # # 4. 定期更换密码（这需要具体的规则，比如一定时间内强制更换）
    egrep -q "^PASS_MAX_DAYS" ${LOGIN_DEFS} || return
    local actual_value1
    actual_value1=$(egrep "^PASS_MAX_DAYS" ${LOGIN_DEFS} | awk '{print $2}')
    [[ ${actual_value} -le 365 ]] ||  return
    
    # # 5. 设置密码最短修改时间
    egrep -q "^PASS_MIN_DAYS" ${LOGIN_DEFS} || return
    local actual_value2
    actual_value2=$(egrep "^PASS_MIN_DAYS" ${LOGIN_DEFS} | awk '{print $2}')
    [[ ${actual_value2} -gt 1 ]] || return
    
    # # 6. 限制密码重用（这需要具体的规则，比如禁止最近几次的密码）
    [[ $(grep -E '^\s*password\s+required\s+pam_pwhistory\.so\s+([^#]+\s+)?remember=([5-9]|[1-9][0-9]+)\b' ${PASS_AUTH}) ]] || return
    
    # # 7. 确保root是唯一的UID为0的帐户
    [[ $(awk -F: '($3 == 0) { print $1 }' $PASSWD) == "root" ]] || return
}

test_ssh_param_le() {
  local parameter="${1}" 
  local allowed_max="${2}"
  local actual_value
  actual_value=$(cut -d\# -f1 ${SSHD_CFG} | grep "${parameter}" | cut -d" " -f2)
  [[ ${actual_value} -le ${allowed_max} ]] || return 
}

#应具有登录失败处理功能，应配置并启用结束会话、限制非法登录次数和当登录连接超时自动退出等相关措施
test_login_security() {
    # 1. 检查是否配置登录失败锁定策略
    [[ $(grep "pam_tally2" ${PASS_AUTH}) ]] || return
    [[ $(grep -E "pam_(tally2|deny)\.so" ${PASS_AUTH}) ]] || return
    
    # 2. 检查是否设置空闲会话断开时间
    local output1="" output2=""

    for f in "$BRC" /etc/profile /etc/profile.d/*.sh; do
    grep -Pq '^\s*([^#]+\s+)?TMOUT=(900|[1-8][0-9][0-9]|[1-9][0-9]|[1-9])\b' "$f" &&
    grep -Pq '^\s*([^#]+;\s*)?readonly\s+TMOUT(\s+|\s*;|\s*$|=(900|[1-8][0-9][0-9]|[1-9][0-9]|[1-9]))\b' "$f" &&
    grep -Pq '^\s*([^#]+;\s*)?export\s+TMOUT(\s+|\s*;|\s*$|=(900|[1-8][0-9][0-9]|[1-9][0-9]|[1-9]))\b' "$f" &&
    output1="$f"
    done

    grep -Pq '^\s*([^#]+\s+)?TMOUT=(9[0-9][1-9]|9[1-9][0-9]|0+|[1-9]\d{3,})\b' /etc/profile /etc/profile.d/*.sh "$BRC" &&
    output2=$(grep -Ps '^\s*([^#]+\s+)?TMOUT=(9[0-9][1-9]|9[1-9][0-9]|0+|[1-9]\d{3,})\b' /etc/profile /etc/profile.d/*.sh $BRC)

    if [ -n "$output1" ] && [ -z "$output2" ]; then
    return 0 # 合规，返回0
    else
    return 1 # 不合规，返回1
    fi

    # 3. 检查是否启用登录时间过期后断开连接设置
    test_ssh_param_le MaxAuthTries 5
}

#当对服务器进行远程管理时，应采取必要措施，防止鉴别信息在网络传输过程中被窃听
test_disable_telnet(){
  test_service_enabled_norun "telnet"
}

#应采用免受恶意代码攻击的技术措施或主动免疫可信验证机制及时识别入侵和病毒行为，并将其有效阻断。


